﻿/* 
Copyright (c) 2009, Aaron Moline <Aaron.Moline@MolineSoftware.com>

Permission is hereby granted, free of charge, to any person 
obtaining a copy of this software and associated documentation 
files (the "Software"), to deal in the Software without restriction, 
including without limitation the rights to use, copy, modify, merge, 
publish, distribute, sublicense, and/or sell copies of the Software, 
and to permit persons to whom the Software is furnished to do so, 
subject to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using MolineSoftware.DrupalXmlRpc;
using CookComputing.XmlRpc;

namespace MolineSoftware.DrupalXml.Example
{
    public partial class frmMain : Form
    {
        #region | Private Properties |
        private DrupalService service;
        private bool connected = false;
        private CustomNode node;
        #endregion

        #region | Constructor |
        public frmMain()
        {
            InitializeComponent();

           // development 
            this.FormClosing += //Close the Connection, if open.
                new FormClosingEventHandler(frmMain_FormClosing);

            foreach (TextBox tb in panel1.Controls.OfType<TextBox>())
            {
                tb.Validating += new CancelEventHandler(tb_Validating);                
            }

        }


        
        #endregion

        #region | Control Events |

        void tb_Validating(object sender, CancelEventArgs e)
        {
            if (string.IsNullOrEmpty(((TextBox)sender).Text))
                ((TextBox)sender).BackColor = Color.Yellow;
            else
                ((TextBox)sender).BackColor = Color.White;
        }

        void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (connected)
                    service.Logout(false);
            }
            catch { }
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            try
            {
                //Check to see that all informatioin is filled in
                foreach (TextBox tb in panel1.Controls.OfType<TextBox>())
                {
                    if(tb.BackColor == Color.Yellow)
                    {
                        MessageBox.Show("You must fill in all information");
                        tb.Focus();
                        return;
                    }
                }

                this.Cursor = Cursors.WaitCursor;

                if (!connected)
                {
                    service = new DrupalService(this.txtServiceKey.Text,
                        this.txtServiceDomain.Text, this.txtServiceURL.Text);

                    service.Connect(false);
                    service.Login(txtUsername.Text, txtPassword.Text, false);
                    btnGo.Text = "Disconnect";
                    tsslUser.Text = "Logged in As: " + service.LoginInfo.User.UserName;
                    tsslUser.BackColor = Color.Green;
                    connected = true;
                    btnGetNode.Enabled = true;
                }
                else
                {
                    service.Logout(false);
                    btnGo.Text = "Connect";
                    tsslUser.Text = "Disconnected";
                    tsslUser.BackColor = Color.Red;
                    connected = false;
                    btnGetNode.Enabled = false;
                    btnSaveNode.Enabled = false;
                    btnDeleteNode.Enabled = false;
                }

            }
            catch (Exception ex)
            {
                ErrorHandler(ex);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void btnGetNode_Click(object sender, EventArgs e)
        {
            try
            {
                node = service.GetNode<CustomNode>(Convert.ToInt32(txtNodeID.Text), DrupalNode.AllFields, false);
                this.rtbNodeBody.Text = node.Body;

                if (node.CustomText[0].HasValue("value", "value"))
                    this.rtbCustomText.Text = node.CustomText.ToValue();

                this.txtTitle.Text = node.Title;
                this.btnDeleteNode.Enabled = true;
            }
            catch (Exception ex)
            {
                ErrorHandler(ex);
            }
        }

        private void rtbNodeBody_TextChanged(object sender, EventArgs e)
        {
            btnSaveNode.Enabled = true;
        }

        private void btnSaveNode_Click(object sender, EventArgs e)
        {
            try
            {

                if (node == null && !string.IsNullOrEmpty(txtNodeID.Text))
                    return;

                if (string.IsNullOrEmpty(txtNodeID.Text))
                {
                    node = new CustomNode();
                }
                else if (node != null)
                {
                    //Get the Node Again to make sure the token hasn't expired.
                    node = service.GetNode<CustomNode>(Convert.ToInt32(node.NodeID), CustomNode.AllFields, false);
                }

                node.Title = this.txtTitle.Text;
                node.CustomText.AddValue(this.rtbCustomText.Text);
                node.Body = this.rtbNodeBody.Text;
                node.ChangeDate = DrupalService.GetUnixTimestamp().ToString();
                node.RevisionDate = DrupalService.GetUnixTimestamp().ToString();
                node.UserID = service.LoginInfo.User.UserID.ToString();
                node.UserName = service.LoginInfo.User.UserName;

                string mesage = service.SaveNode<DrupalNode>(node, false);
                MessageBox.Show(string.Format("Saved Node. NodeID: {0}", mesage),
                    "Node Save", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            catch (Exception ex)
            {
                ErrorHandler(ex);
            }
        }

        private void btnDeleteNode_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show(string.Format("Are you sure you want to delete {0}", txtTitle.Text), "Node Deletion",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    string msg = service.NodeDelete(Convert.ToInt32(txtNodeID.Text), false);
                    MessageBox.Show(msg, "Node Deletion", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

            }
            catch (Exception ex)
            {
                ErrorHandler(ex);
            }
        }
        #endregion

        #region | Private Methods |
        private void ErrorHandler(Exception ex)
        {
            MessageBox.Show(ex.Message.ToString(), "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }


        #endregion
    }
}
